import React, { useEffect, useState } from "react";
import qs from "qs";
import { useLocation, useNavigate } from "react-router-dom";
import axios from "axios";
import { Button, Loading } from "react-vant";
import { useDispatch } from "react-redux";
import { tradeSuccessActionCreator } from "../../store/user/userReducer";
const Index: React.FC = () => {
  const { search } = useLocation();
  const [loading, setLoading] = useState(true);
  const { out_trade_no, trade_no } = qs.parse(search.slice(1));
  const [message, setMessage] = useState();
	const navigate = useNavigate()
	const dispatch = useDispatch()
  const query = async () => {
    try {
      const resp = await axios.get("/api/order/query", {
        params: { out_trade_no, trade_no },
      });
      const { message, code, data } = resp.data;
			setMessage(message);
      if (code === 200) {
				const { tradeStatus, outTradeNo } = data;
				if(tradeStatus === "TRADE_SUCCESS") {
					dispatch(tradeSuccessActionCreator(outTradeNo))
				}
      }
    } catch (err) {
      console.log("请求报错", err);
    }
    setLoading(false);
  };

  useEffect(() => {
    query();
  }, []);

  if (loading) {
    return (
      <div>
        <Loading></Loading>
      </div>
    );
  }
  return (
    <div>
      <h2>支付结果: {message ? message: <Loading></Loading>}</h2>
      <Button type="primary" onClick={() => navigate('/')}>再去逛逛</Button>
    </div>
  );
};

export default Index;
